import type { FormRules } from "naive-ui";
import { isEmpty } from "@/utils";
import {
  REGEXP_CODE_SIX,
  REGEXP_EMAIL,
  REGEXP_PHONE,
  REGEXP_PWD,
} from "@/utils";

/** 创建自定义错误信息的必填表单规则 */
const requiredRule = (message: string) => ({
  required: true,
  message,
  trigger: "input",
});

const formRules = {
  phone: [
    requiredRule("请输入手机号码"),
    { pattern: REGEXP_PHONE, message: "手机号码格式错误", trigger: "input" },
  ],
  email: [
    requiredRule("请输入邮箱号"),
    { pattern: REGEXP_EMAIL, message: "邮箱格式错误", trigger: "blur" },
  ],
  password: [
    requiredRule("请输入密码"),
    {
      pattern: REGEXP_PWD,
      message: "密码为6-18位数字/字符/符号，至少2种组合",
      trigger: "input",
    },
  ],
  code: [
    requiredRule("请输入验证码"),
    { pattern: REGEXP_CODE_SIX, message: "验证码格式错误", trigger: "input" },
  ],
};

export const rulesCode: FormRules = {
  phone: formRules.phone,
  code: formRules.code,
  imgCode: requiredRule("请输入验证码"),
};

export const rulesPwd: FormRules = {
  account: requiredRule("请输入账号"),
  password: formRules.password,
  captchaCode: requiredRule("请输入验证码"),
};

export const createRulesReset = (password: Ref<string>): FormRules => ({
  phone: formRules.phone,
  code: requiredRule("请输入验证码"),
  password: formRules.password,
  confirmPassword: [
    { required: true, message: "请输入确认密码" },
    {
      message: "输入的值与密码不一致",
      trigger: "input",
      validator: (rule, value) => {
        if (!isEmpty(value) && value !== password.value) {
          return Promise.reject(rule.message);
        }
        return Promise.resolve();
      },
    },
  ],
});
